package cn.quevo.beetlsql;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.beetl.sql.core.JavaType;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.mapping.BeanProcessor;
import org.beetl.sql.core.mapping.type.JavaSqlTypeHandler;
import org.beetl.sql.core.mapping.type.TypeParameter;

/**
 * BeetlSQL 结果集转MAP
 * 
 * @author July july_sky@foxmail.com
 * @date 2017年12月14日 下午11:25:11
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @version 1.0
 */
public class BeetlBeanProcessor extends BeanProcessor {

	public BeetlBeanProcessor(SQLManager sm) {
		super(sm);
	}

	@SuppressWarnings("unchecked")
	private Map<String,Object> getMapIns(Class<?> clazz){
		if(clazz==Map.class){
			return new HashMap<>();
		}
		try {
			return (Map<String, Object>)clazz.newInstance();
		} catch (Exception e) {
			return null;
		} 
	}
	
	@Override
	public Map<String, Object> toMap(String sqlId, Class<?> c, ResultSet rs) throws SQLException {
		Map<String, Object> result = this.getMapIns(c);
		if(c==null){
			throw new SQLException("不能映射成Map:"+c);
		}
		
		ResultSetMetaData rsmd = rs.getMetaData();
		int cols = rsmd.getColumnCount();
//		String tableName = nc.getTableName(c);
		TypeParameter tp = new TypeParameter(sqlId,dbName,null,rs,rsmd,0);
		for (int i = 1; i <= cols; i++) {
			String columnName = rsmd.getColumnLabel(i);
			if (null == columnName || 0 == columnName.length()) {
				columnName = rsmd.getColumnName(i);
			}
			int colType = rsmd.getColumnType(i);
			Class<?>  classType = JavaType.jdbcJavaTypes.get(colType);
			JavaSqlTypeHandler handler = handlers.get(classType);
			if(handler==null){
				handler = this.defaultHandler;
			}
			tp.setIndex(i);
			tp.setTarget(classType);
			Object value = handler.getValue(tp);
			result.put(this.nc.getPropertyName(c,columnName), value);
		}
		return result;
	}
}
